package com.acceptable.qucun.user.service.impl;

import com.acceptable.qucun.file.mapper.*;
import com.acceptable.qucun.file.service.impl.TemplateFileServiceImpl;
import com.acceptable.qucun.generic.entity.FileItem;
import com.acceptable.qucun.generic.entity.UserItem;
import com.acceptable.qucun.generic.util.TimeUtil;
import com.acceptable.qucun.user.entity.User;
import com.acceptable.qucun.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;

@Service
public class UserDatabaseOperation {
    @Autowired private UserMapper userMapper;
    @Autowired private TemplateFileMapper fileMapper;
    @Autowired private FileSourceMapper sourceMapper;
    @Autowired private FileShareMapper shareMapper;
    @Autowired private FileShareItemMapper shareItemMapper;
    @Autowired private FileDeleteMapper deleteMapper;

    @Autowired private TemplateFileServiceImpl fileService;
    @Autowired private FileItem fileItem;
    @Autowired private UserItem userItem;

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public boolean deleteUserByEmail(@NonNull String email){
        User user = userMapper.selectByEmail(email);
        return this.deleteUser(user);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public boolean deleteUserByUserId(@NonNull Integer userId){
        User user = userMapper.selectByUserId(userId);
        return this.deleteUser(user);
    }

    private boolean deleteUser(@NonNull User user){
        LocalDateTime endTime = user.getDeleteTime();
        if (!user.getDeleted() || endTime == null)
            return false;

        endTime = endTime.plusDays(userItem.getMaxRestDay());
        Date now = new Date();
        if (now.before(TimeUtil.localDateTime2Date(endTime))){
            return false;
        }

        Integer userId = user.getUserId();
        shareItemMapper.dropTable(userId);
        deleteMapper.dropTable(userId);
        fileMapper.dropTable(userId);

        sourceMapper.deleteBatchByUserId(userId);
        shareMapper.deleteBatchByUserId(userId);
        userMapper.deleteByUserId(userId);
        return true;
    }
}
